package com.jmult.crop;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.FileKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.jmult.crop.model.ImageModel;
import com.jmult.kit.ImageCropKit;

public class CropperService {

	private String uploadPath = PathKit.getWebRootPath();

	// 用户上传图片最多只允许 8M大小
	public int getImageMaxSize() {
		return 1024 * 1024 * 8;
	}

	public Page<ImageModel> getUploadImages(int pageNumber) {

		List<ImageModel> images = new ArrayList<ImageModel>();

		traverseFolder(uploadPath + File.separator + "upload", images);
		Collections.sort(images);

		int pageSize = 8;
		int totalRow = images.size();
		int totalPage = totalRow > pageSize ? (totalRow % pageSize > 0 ? totalRow / pageSize + 1 : totalRow / pageSize)
				: 1;

		int fromIndex = 0;
		int toIndex = 0;

		if (pageNumber > totalPage)
			pageNumber = totalPage;

		if (pageNumber == 1) {
			fromIndex = 0;
			toIndex = totalPage > 1 ? pageSize : totalRow;
		} else if (pageNumber < totalPage) {
			fromIndex = pageSize * (pageNumber - 1);
			toIndex = pageSize * pageNumber;
		} else {
			fromIndex = pageSize * (pageNumber - 1) - 1;
			toIndex = totalRow;
		}

		if (images.size() > 0)
			images = images.subList(fromIndex, toIndex);

		return new Page<ImageModel>(images, pageNumber, pageSize, totalPage, totalRow);
	}

	private void traverseFolder(String path, List<ImageModel> images) {
		File file = new File(path);
		if (file.exists()) {
			File[] files = file.listFiles();
			if (null == files || files.length == 0) {
				// System.out.println("上传文件夹是空的");
				return;
			} else {
				for (File file2 : files) {
					if (file2.isDirectory()) {
						// System.out.println("文件夹：" + file2.getAbsolutePath());
						traverseFolder(file2.getAbsolutePath(), images);
					} else {
						if (!file2.isHidden())
							images.add(new ImageModel(file2.getName(), file2.lastModified(),
									new Date(file2.lastModified()),
									file2.getAbsolutePath().replace(uploadPath, "").replace("\\", "/")));
					}
				}

			}
		}
	}

	@SuppressWarnings("unchecked")
	public Ret cropImage(String putData, UploadFile file) {
		HashMap<String, Integer> jsonMap = JSON.parseObject(putData, HashMap.class);

		int x = Integer.parseInt(new DecimalFormat("0").format(jsonMap.get("x")));
		int y = Integer.parseInt(new DecimalFormat("0").format(jsonMap.get("y")));
		int width = Integer.parseInt(new DecimalFormat("0").format(jsonMap.get("width")));
		int height = Integer.parseInt(new DecimalFormat("0").format(jsonMap.get("height")));
		int rotate = Integer.parseInt(new DecimalFormat("0").format(jsonMap.get("rotate")));

		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
		String cropSuffix = file.getFileName().substring(file.getFileName().lastIndexOf("."));
		String cropName = fmt.format(new Date()) + cropSuffix;
		String savePath = file.getUploadPath() + File.separator + "crop" + File.separator + cropName;

		try {
			ImageCropKit.cropImage(file.getFile(), savePath, x, y, width, height, rotate, file.getContentType());
			FileKit.delete(file.getFile());
			return Ret.ok("msg", "图片处理成功");
		} catch (IOException e) {
			FileKit.delete(file.getFile());
			return Ret.fail("msg", e.getMessage());
		}
	}

}